{extend name="public/base"/}
{block name="style"}
<link rel="stylesheet" href="__PUBLIC__/css/order.css">
<style>
    #order-more-btn {top: 30px;line-height: 30px;}
    #order-more-btn button { width: 100%;}
 </style>
{/block}
{block name="content"}
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12 Order">
            <div class="layui-card">
                <div class="layui-card-body">
                    <div class="layui-tab">
                        <div class="layui-tab-content">
                            <div class="layui-tab-item screen-box">
                                <div class="layui-form-item channel order-select">
                                    <label class="layui-form-label">平台</label>
                                    <div class="layui-input-block">
                                        <ul>
                                            <li item="platform_name="><a class="active">全部</a></li>
                                            {foreach name="platform" id="p"}
                                                <li item="platform_name={$p->name}"><a>{$p->name}</a></li>
                                            {/foreach}
                                        </ul>
                                    </div>
                                </div>
                                {php}if(!isset($other_filter)):{/php}
                                <div class="layui-form-item channel order-select">
                                    <label class="layui-form-label">订单状态</label>
                                    <div class="layui-input-block">
                                        <ul>
                                            <li item="order_status="><a class="active">全部</a></li>
                                            {foreach name="order_status" id="p" key="k"}
                                                <li item="order_status={$k}"><a>{$p}</a></li>
                                            {/foreach}
                                        </ul>
                                    </div>
                                </div>
                                {php}endif;{/php}
                                <div class="layui-form-item channel order-select">
                                    <label class="layui-form-label">发货状态</label>
                                    <div class="layui-input-block">
                                        <ul>
                                            <li item="send_status="><a class="active">全部</a></li>
                                            {foreach name="send_status" id="p" key="k"}
                                                <li item="send_status={$k}"><a>{$p}</a></li>
                                            {/foreach}
                                        </ul>
                                    </div>
                                </div>
                                <div class="layui-form-item channel order-select">
                                    <label class="layui-form-label">面单状态</label>
                                    <div class="layui-input-block">
                                        <ul>
                                            <li item="send_status="><a class="active">全部</a></li>
                                            {foreach name="label_status" id="p" key="k"}
                                            <li item="label_url={$k}"><a>{$p}</a></li>
                                            {/foreach}
                                            {foreach name="print_status" id="p" key="k"}
                                            <li item="is_print={$k}"><a>{$p}</a></li>
                                            {/foreach}
                                        </ul>
                                    </div>
                                </div>
                                <div class="layui-form-item channel order-select">
                                    <label class="layui-form-label">发货时间</label>
                                    <div class="layui-input-block">
                                        <ul>
                                            <li item="send_date="><a class="active">全部</a></li>
                                            {foreach name="send_date" id="send" key="key"}
                                                <li item="send_date={$key}"><a>{$send}</a></li>
                                            {/foreach}
                                        </ul>
                                    </div>
                                </div>
                                <div class="layui-form-item channel order-select">
                                    <label class="layui-form-label">排序方式</label>
                                    <div class="layui-input-block">
                                        <ul>
                                            <li item="sort="><a class="active">默认</a></li>
                                            {foreach name="sort" id="st" key="key"}
                                                <li item="sort={$key}"><a>{$st}</a></li>
                                            {/foreach}
                                        </ul>
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">订单时间</label>
                                    <div class="layui-input-inline" style="width: 220px;">
                                        <input class="layui-input laydate-range" id="start_date" autocomplete="off" name="date" placeholder="平台生成时间">
                                    </div>
                                    <div class="layui-input-inline" style="width: 220px;">
                                        <input class="layui-input laydate-range" id="create_time" autocomplete="off" name="create_time" placeholder="导入时间">
                                    </div>
                                    <button type="button" class="layui-btn layui-btn layui-btn-normal search-btn"><i
                                            class="layui-icon layui-icon-search"></i></button>
                                </div>
                            </div>
                            <div class="layui-tab-item layui-show">
                                <form class="layui-form">
                                    <div class="layui-col-md1 layui-row">
                                        <select id="select_order" lay-search lay-filter="select_order">
                                            {foreach name="select_order" id="item" key="key"}
                                                <option value="{$key}">{$item}</option>
                                            {/foreach}
                                        </select>
                                    </div>
                                    <div class="layui-col-md2 layui-row">
                                        <input id="order_name" autofocus="autofocus" placeholder="按回车搜索" class="layui-input"/>
                                    </div>
                                    <div class="layui-col-md2 layui-row">
                                        <div class="more-xm-select" name="select-account" tips="账号">
                                            <span class="layui-hide">{$account|json_encode}</span>
                                        </div>
                                    </div>
                                    <div class="layui-col-md1 layui-row">
                                        <div class="more-xm-select" name="select-country" tips="国家">
                                            <span class="layui-hide">{$select_country|json_encode}</span>
                                        </div>
                                    </div>
                                    <!--<div class="layui-col-md1 layui-row">
                                        <div class="more-xm-select" name="select-logistics" tips="物流商">
                                            <span class="layui-hide">{$select_logistics|json_encode}</span>
                                        </div>
                                    </div>-->
                                    <div class="layui-col-md1 layui-row">
                                        <div class="more-xm-select" name="select-channel" tips="渠道">
                                            <span class="layui-hide">{$select_channel|json_encode}</span>
                                        </div>
                                    </div>
                                    <div class="layui-col-md2 layui-row">
                                        <a class="layui-btn layui-btn-normal order-select-down"><span>更多</span>&nbsp;&nbsp;<i
                                                class="fa fa-angle-double-down" aria-hidden="true"></i></a>
                                    </div>
                                    {php}if(isset($other_filter)):{/php}
                                        {foreach name="other_filter" id="filter" key="f"}
                                            <input type="hidden" class="other-filter" name="{$f}" value="{$filter}"/>
                                        {/foreach}
                                    {php}endif;{/php}
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-body">
                    <div class="layui-btn-group">
                        {if $is_show_delete}
                        <button type="button" id="remove-all" class="layui-btn layui-btn-sm layui-btn-normal"><i
                                class="layui-icon layui-icon-delete"></i>批量删除
                        </button>
                        {/if}
                        <a href="/attachment/template/order-template.xlsx?v=1"
                           class="layui-btn layui-btn-sm layui-btn-normal"><i
                                class="layui-icon layui-icon-download-circle"></i>下载模板</a>
                        {if $is_show_import}
                        <button type="button" id="import-order" class="layui-btn layui-btn-sm layui-btn-normal"><i
                                class="layui-icon layui-icon-upload-drag"></i>导入订单
                        </button>
                        {/if}
                        {if $is_show_export}
                        <button type="button" id="export-order" class="layui-btn layui-btn-sm layui-btn-normal"><i
                                class="layui-icon layui-icon-export"></i>导出订单
                        </button>
                        {/if}
                        {if $is_show_platform_import}
                        <button type="button" id="import-platfrom-order" class="layui-btn layui-btn-sm layui-btn-normal"><i
                                class="layui-icon layui-icon-upload-drag"></i>导入亚马逊表格
                        </button>
                        {/if}
                        {if $is_show_batch_print}
                        <button type="button" id="batch-print"  class="layui-btn layui-btn-sm layui-btn-normal"><i
                                class="layui-icon layui-icon-print"></i>打印面单
                        </button>
                        {/if}
                        <ul class="layui-nav layui-bg-green btnz"
                            style="font-size: 12px;border-radius: 0px;float: right;padding:0px;margin-left: 2px;">
                            <li class="layui-nav-item" style="line-height: 30px;font-size: 12px;">
                                <a class="layui-btn layui-btn-sm layui-btn-normal"
                                   style="color:white;font-size: 12px;padding: 0px 30px 0px 20px;">更多<span
                                        class="layui-nav-more" style="right: 10px;font-size: 12px;"></span></a>
                                <dl class="layui-nav-child" id="order-more-btn"> <!-- 二级菜单 -->
                                    <!--<dd>
                                        <button type="button" id="batch-select-chanel"
                                                class="layui-btn layui-btn-sm layui-btn-normal">选择渠道
                                        </button>
                                    </dd>-->
                                    {if $is_show_save}
                                    <dd>
                                        <button type="button" id="batch-edit-status"
                                                class="layui-btn layui-btn-sm layui-btn-normal">修改状态
                                        </button>
                                    </dd>
                                    <dd>
                                        <button type="button" id="batch-remark"
                                                class="layui-btn layui-btn-sm layui-btn-normal">批量备注
                                        </button>
                                    </dd>
                                    {/if}
                                    {if $is_show_declare}
                                    <dd>
                                        <button type="button" id="batch-declare"
                                                class="layui-btn layui-btn-sm layui-btn-normal">申报订单
                                        </button>
                                    </dd>
                                    {/if}
                                    {if $is_show_invoice}
                                    <dd>
                                        <button type="button" id="batch-download-invoice"
                                                class="layui-btn layui-btn-sm layui-btn-normal">下载发票
                                        </button>
                                    </dd>
                                    {/if}
                                    {if $is_show_lock}
                                    <dd>
                                        <button type="button" id="batch-lock"
                                                class="layui-btn layui-btn-sm layui-btn-normal">占用库存
                                        </button>
                                    </dd>
                                    {/if}
                                    {if $is_show_unlock}
                                    <dd>
                                        <button type="button" id="batch-unlock"
                                                class="layui-btn layui-btn-sm layui-btn-normal">释放库存
                                        </button>
                                    </dd>
                                    {/if}
                                    {if $is_show_repair}
                                    <dd>
                                        <button type="button" id="batch-repair"
                                                class="layui-btn layui-btn-sm layui-btn-normal">修复订单
                                        </button>
                                    </dd>
                                    {/if}
                                    {if $is_show_again}
                                    <dd>
                                        <button type="button" id="batch-add-again"
                                                class="layui-btn layui-btn-sm layui-btn-normal">再次发货
                                        </button>
                                    </dd>
                                    {/if}
                                    {if $is_show_purchase}
                                    <dd>
                                        <button type="button" id="batch-purchase"
                                                class="layui-btn layui-btn-sm layui-btn-normal">生成采购单
                                        </button>
                                    </dd>
                                    {/if}
                                    {if $is_show_black}
                                    <dd>
                                        <button type="button" id="batch-add-black"
                                                class="layui-btn layui-btn-sm layui-btn-normal">加入黑名单
                                        </button>
                                    </dd>
                                    {/if}
                                </dl>
                            </li>
                        </ul>
                    </div>
                    <table class="layui-hide" id="commodity" lay-filter="commodity"></table>
                </div>
            </div>
        </div>
    </div>
    <!--操作-->
    <a class="layui-hide ajax-form" id="order-return-btn" title="订单退货" width-form="80%" height-form="80%"></a>
    <a class="layui-hide ajax-form" id="order-again-btn" title="再次发货" width-form="80%" height-form="80%"></a>
    <script type="text/html" id="operation">
        <div>
            <button style="margin-bottom: 3px;" lay-event="look" type="button" class="layui-btn layui-btn-sm"><i
                class="layui-icon layui-icon-search"></i></button>
            <br>
            <button style="margin-bottom: 3px;" lay-event="edit" type="button"
                    class="layui-btn layui-btn-sm layui-btn-warm"><i class="layui-icon layui-icon-edit"></i></button>
            <!--<button style="margin-bottom: 3px;" lay-event="print" type="button"
                    class="layui-btn layui-btn-sm layui-btn-normal"><i class="layui-icon layui-icon-print"></i></button>
            <br>
            {if $is_show_delete}
            <br>
            <button type="button" lay-event="del" class="layui-btn layui-btn-sm layui-btn-danger"><i
                    class="layui-icon layui-icon-delete"></i></button>
            {/if}-->
            {if $is_show_return}
                <!-- 退货 -->
                <br>
                <button style="margin-bottom: 3px;" type="button" lay-event="ret" class="layui-btn layui-btn-sm layui-bg-cyan"><i
                        class="layui-icon layui-icon-return"></i>
                </button>
            {/if}
            {if $is_show_again}
            <!-- 再次发货 -->
                <br>
                <button style="margin-bottom: 3px;" type="button" lay-event="again" class="layui-btn layui-btn-sm layui-bg-red"><i
                        class="layui-icon layui-icon-reply-fill"></i>
                </button>
            {/if}
        </div>
    </script>
    <!-- 修改订单状态-->
    <script type="text/html" id="edit-order-status">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-body">
                    <div class="layui-form-item channel order-status-select">
                        <label class="layui-form-label">订单状态</label>
                        <div class="layui-input-block">
                            <ul>
                                {foreach name="allow_order_status" id="s"}
                                    <li item="order_status={$s}"><a>{php}echo \app\common\model\Orders::$ORDER_STATUS[$s];{/php}</a></li>
                                {/foreach}
                            </ul>
                        </div>
                    </div>
                    <div class="layui-form-item channel order-status-select">
                        <label class="layui-form-label">发货状态</label>
                        <div class="layui-input-block">
                            <ul>
                                {foreach name="allow_order_send" id="s"}
                                    <li item="send_status={$s}"><a>{php}echo \app\common\model\Orders::$SEND_STATUS[$s];{/php}</a></li>
                                {/foreach}
                            </ul>
                        </div>
                    </div>
                    <form class="layui-form">
                        <div class="layui-form-item">
                            <label class="layui-form-label">物流商</label>
                            <div class="layui-input-inline">
                                <select id="logistics_name" lay-filter="carrier" lay-search>
                                    <option value="">请选择</option>
                                    {foreach name="carrier" id="c"}
                                        <option value="{$c.carrier_id}">{$c.carrier_name}</option>
                                    {/foreach}
                                </select>
                            </div>
                            <div class="layui-input-inline">
                                <select id="channel_id" lay-search>
                                    <option value="">请选择</option>
                                </select>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </script>
    <!--导入平台订单-->
    <script type="text/html" id="platform-order-excel">
        <form class="layui-form">
            <div class="layui-form-item">
                <label class="layui-form-label">账号</label>
                <div class="layui-input-inline">
                    <select id="platform-account-order" lay-search>
                        <option value="">请选择账号</option>
                        {foreach name="account" id="a"}
                        <option value="{$a.account_id}">{$a.username ?: $a.store_name}</option>
                        {/foreach}
                    </select>
                    <p style="color: red; display: none;" id="platform-order-error-msg">请先选择账号</p>
                </div>
                <div class="layui-input-inline">
                    <button type="button" id="import-platfrom-order-excel" class="layui-btn layui-btn-normal"><i
                            class="layui-icon layui-icon-upload-drag"></i>选择文件
                    </button>
                </div>
            </div>
        </form>
    </script>
{/block}
{block name="script"}
<link rel="stylesheet" href="__PUBLIC__/css/print.min.css">
<script type="text/javascript" src="__PUBLIC__/js/print.min.js"></script>
<script type="text/javascript">
    layui.extend({
        xmSelect: 'xm-select'
    }).use(['form', 'laydate', 'table', 'upload', 'layer', 'longli', 'xmSelect', 'jquery'], function ()
    {
        var form = layui.form
            , layer = layui.layer
            , table = layui.table
            , upload = layui.upload
            , $ = layui.jquery;

        //展示已知数据
        table.render({
            elem: '#commodity'
            , page: true
            , url: '{:url("order/manager/index")}?' + $.param(getOtherFilter())
            //, toolbar: '#toolbarDemo'
            , title: '订单数据表'
            , height: 'full-200'
            , cols: [[ //标题栏
                {type: 'checkbox'},
                {
                    field: 'info', title: '商品信息', width: 300, templet: function (row) {
                        var html = "";
                        for (let i in row.detail) {
                            let line = row.detail[i];
                            html += `<div style="display: flex; margin-bottom: 10px;">
                            <div><a ${line.url ? 'target="_blank"' : ''} href="${line.url ? line.url : 'javascript:void(0)'}"><img src="${line.image_url}"></a></div>
                            <div style="margin-left: 10px;">
                                <h3 style="color: #428bca;"><a ${line.url ? 'target="_blank"' : ''} href="${line.url ? line.url : 'javascript:void(0)'}">${line.name_ch ? line.name_ch : line.name}</a></h3>
                                <div style="display: flex;flex-wrap: wrap">
                                    <p style="margin: 3px">币种：<span class="layui-badge layui-bg-green">${row.currcode?row.currcode.currency_name:row.currency}</span></p>
                                    <p style="margin: 3px">数量：<span class="layui-badge layui-bg-blue">${line.qty}</span></p>
                                    <p style="margin: 3px">属性：<span>${line.attr}</span></p>
                                    <p style="margin: 3px">SKU：<span class="layui-badge layui-bg-green copy-text">${line.sku}</span></p>
                                    <p style="margin: 3px">平台SKU：<span class="layui-badge layui-bg-cyan copy-text">${line.platform_sku}</span></p>
                                </div>
                            </div>
                        </div>`;
                        }
                        return html;
                    }
                }
                ,{
                    field: "total_price", title: "总金额", templet:function (row) {
                        return `<p>${row.currcode?row.currcode.currency_name:row.currency}：${row.total_price}</p>
                                <p>人民币：${row.total_price_rmb > 0 ? row.total_price_rmb : ''}</p>
                                `;
                    }
                }
                , {
                    field: 'address', title: '收件人', templet: function (row) {
                        var s = row.consignee ? row.consignee : row.buyer_first_name + ' ' + row.buyer_last_name;
                        return `<p>收件人：${s}</p>
                                <p>邮箱：<span class="copy-text">${row.buyer_email}</span></p>
                                <p>国家：${row.buyer_country ? row.buyer_country : row.buyer_country_code}</p>
                                <!--<p>城市：${row.buyer_city ? row.buyer_city : ''}</p>-->
                                <!--<p>地址：${row.buyer_address_1}</p>-->
                                `;
                    }
                }
                , {
                    field: 'order_no', width: 200, title: '订单号', templet: function (row) {
                        return `<div>
                                 <p>平台：${row.platform_name}</p>
                                 <p>账号：${row.account.username}</p>
                                 <p>平台订单号：<span class="copy-text">${row.order_no}</span></p>
                                 <p>内部订单号：<span class="copy-text">${row.order_sn}</span></p>
                            </div>`;
                    }
                }
                , {
                    field: 'date', title: '时间', width: 200, templet: function (row) {
                        return `<div>
                                <p>下单：${row.order_source_create_time ? row.order_source_create_time : ''}</p>
                                <p>付款：${row.order_pay_time ? row.order_pay_time : ''}</p>
                                <p>发货：${row.shipping_time ? row.shipping_time : ''}</p>
                                <p>导入：<span class="layui-badge layui-bg-blue">${row.create_time.substr(0, 10)}</span></p>
                                <p>最迟发货：<span class="layui-badge">${row.latest_delivery_time ? row.latest_delivery_time.substr(0, 10) : ''}</span></p>
                            </div>`;
                    }
                }
                , {
                    field: 'method', title: '物流方式', templet: function (row) {
                        var track = row.track_num ? `<span class="copy-text">${row.track_num}</span>` : '';
                        return `
                            <p style="margin: 3px">重量：<span class="layui-badge layui-bg-blue">${row.weight}克</span></p>
                            <p>渠道：${row.shipping_method}</p>
                            <p>追踪号：${track}</p>
                            <p>是否生成：<span class="layui-badge">${row.label_url?'是':'否'}</span></p>
                            <p>是否打印：<span class="layui-badge layui-bg-green">${row.is_print}</span></p>
                            `;
                    }
                }
                , {
                    field: 'status', width: 150, title: '状态', templet: function (row) {
                        return `
                            <p style="margin: 5px; text-align: center;">订单：<span class="layui-badge">${row.order_status}</span></p>
                            <p style="margin: 5px; text-align: center;">发货：<span class="layui-badge layui-bg-cyan">${row.send_status}</span></p>
                            <p style="margin: 5px; text-align: center;">平台：<span class="layui-badge layui-bg-orange">${row.order_platform_status}</span></p>
                            `;
                    }
                }
                , {field: 'platform_remark', title: '买家备注'}
                , {field: 'remark', title: '备注', edit: 'text'}
                , {field: 'experience', title: '操作', width: 70, fixed: "right", toolbar: '#operation'}
            ]]
            //,skin: 'line' //表格风格
            , even: true
            , limits: [100, 150, 300, 500, 5000]
            , limit: 100 //每页默认显示的数量
        });

        //监听单元格编辑
        table.on('edit(commodity)', function (obj) {
            var value = obj.value //得到修改后的值
                , data = obj.data //得到所在行所有键值
                , field = obj.field; //得到字段
            var params = {field, value};
            params["order_id"] = data.order_id;
            $.post("{:url('/order/manager/save')}", params).done(function(response)
            {
                var icon = response.code == 1 ? 6 : 5;
                layer.msg(response.msg, {icon: icon, time: 1500});
            });
        });

        // 订单搜索
        $(".search-btn").click(function () {
            var $where = {};
            $("div.order-select li a.active").each(function (i, e) {
                var item = $(e).parent().attr("item").split("=");
                if (item[1]) $where[item[0]] = item[1];
            });
            var logistics = $("input[name='select-logistics']").val(),
                channel = $("input[name='select-channel']").val(),
                country = $("input[name='select-country']").val(),
                account = $("input[name='select-account']").val(),
                orderVal = $("#order_name").val().trim(),
                create_time = $("#create_time").val().trim(),
                start_date = $("#start_date").val().trim();
            if (orderVal) $where[$("#select_order option:selected").val()] = orderVal;
            if (country) $where["buyer_country_code"] = country;
            if (channel) $where["channel_id"] = channel;
            if (account) $where["account_id"] = account;
            if (logistics) $where["logistics_name"] = logistics;
            if (start_date) $where["start_date"] = start_date;
            if (create_time) $where["create_time"] = create_time;
            $where = $.extend($where, getOtherFilter());
            // if($.isEmptyObject($where)) return;
            var url = "{:url('/order/manager/index')}" + ($.isEmptyObject($where) ? "" : "?" + $.param($where));
            table.reload("commodity", {
                url: url,
                page: {
                    curr: 1 //重新从第 1 页开始
                },
                // where: $where,
                // done: function(){console.log(this.where);}
            });
            return false;
        });
        // 监听搜索下拉框
        form.on('select(search)', function (data) {
            if (data.value != "") reloadOrderTable();
        });
        form.on('select(select_order)', function (data) {
            if ($("#order_name").val().trim() != "") reloadOrderTable();
        });

        // 监听输入框回车
        $("#order_name").keydown(function (event) {
            if (event.keyCode == 13)
            {
                reloadOrderTable();
                $(this).val('');
            }
        });

        //监听行工具事件
        table.on('tool(commodity)', function (obj) {
            var data = obj.data;
            if (obj.event === 'del') {
                layer.confirm('真的删除订单？', function (index) {
                    deleteOrder(data.order_id, function () {
                        obj.del();
                        layer.close(index);
                    });
                });
            } else if (obj.event === 'print') {
                if (data.label_url.length < 1) {
                    layer.msg("未生成面单", {icon: 5, time: 1500});
                    return;
                }
                printLabel(data.order_id);
                $("#order_name").focus();
            } else if (obj.event === 'edit') {
                openEditOrderStatus(function(params)
                {
                    params["order_id"] = data.order_id;
                    $.post("{:url('/order/manager/save')}", params).done(function (response) {
                        var icon = response.code == 1 ? 6 : 5;
                        layer.msg(response.msg, {icon: icon, time: 1500});
                        //if(response.code == 1) reloadOrderTable();
                    });
                });
            } else if (obj.event === 'look') {
                layer.open({
                    type: 2,
                    title: '订单详情',
                    area: ['80%', '80%'],
                    content: '{:url("order/manager/look")}?order_id=' + data.order_id
                });
            }
            else if(obj.event == 'ret')
            {
                // 退货
                $("#order-return-btn")
                    .attr('href', "{:url('order_return')}?order_id="  + data.order_id)
                    .click();
            }
            else if(obj.event == 'again')
            {
                // 再次发货
                $("#order-again-btn")
                    .attr('href', "{:url('again')}?order_id="  + data.order_id)
                    .click();
            }
        });

        function getOtherFilter()
        {
            var other = {};
            $("input.other-filter").each(function()
            {
                other[$(this).attr("name")] = $(this).val();
            });
            return other;
        }
        // 打开弹窗更新订单状态
        function openEditOrderStatus(fn)
        {
            layer.open({
                title: '修改订单状态',
                area: ['80%', '60%'],
                content: $("#edit-order-status").html()
                , success: function (layero, index) {
                    form.render('select');
                    form.on('select(carrier)', function(data)
                    {
                        if(!data.value) return false;
                        $.get("{:url('cha/channel/channel_list')}", {carrier_id:data.value}).done(function(response)
                        {
                            if(response.code == 1)
                            {
                                var data = response.data;
                                var html = ["<option value=''>请选择</option>"];
                                for(let i in data)
                                {
                                    html.push("<option value='" + data[i].channel_id + "'>" + data[i].channel_name + "</option>");
                                }
                                $("#channel_id").html(html.join(""));
                                form.render('select');
                            }
                        });
                    });
                }
                , yes: function (index, layero) {
                    var params = {
                        "field": [],
                        "value": []
                    };
                    $(".order-status-select .active").each(function () {
                        let t = $(this).parent().attr("item").split("=");
                        params.field.push(t[0]);
                        params.value.push(t[1]);
                    });
                    var logistics = $("#logistics_name option:selected").val(),
                        channel = $("#channel_id option:selected").val();
                    if(logistics && channel)
                    {
                        params.field.push("logistics_name");
                        params.value.push($("#logistics_name option:selected").text());
                        params.field.push("channel_id");
                        params.value.push(channel);
                    }
                    layer.close(index);
                    if(params.field.length < 1) return;
                    if(typeof fn === "function") fn(params);
                }
            });
        }
        // 刷新表格订单
        function reloadOrderTable() {
            $(".search-btn").click();
            form.render('select');
        }

        /**
         * 删除订单
         * @param orderId  订单id 可多个
         * @param fn 回调函数
         */
        function deleteOrder(orderId, fn) {
            $.get("{:url('order/manager/delete')}", {ids: orderId}).done(function (response) {
                var icon = response.code == 1 ? 6 : 5;
                if(response.code == 1)
                {
                    layer.msg(response.msg, {icon: icon, time: 1500}, fn ? fn : null);
                }
                else
                {
                    layer.msg(response.msg, {icon: icon, time: 1500});
                }
            });
        }

        // 导入订单
        upload.render({
            elem: '#import-order'
            , url: '{:url("file/upload",["type"=>"document"])}'
            , accept: 'file' //普通文件
            , exts: 'xlsx|xls|csv' // 指定类型
            , field: "file"
            , before: function (obj) {
                layer.load(0, {shade: false});
            }
            , done: function (response, index, upload) {
                if (response.code != 1) {
                    layer.closeAll('loading');
                    var icon = response.code == 1 ? 6 : 5;
                    layer.msg(response.msg, {icon: icon, time: 1500});
                    return;
                }
                $.post("{:url('order/manager/import')}", {"path": response.data.src}).done(function (response) {
                    layer.closeAll('loading');
                    var icon = 5, time = 5500;
                    if (response.code == 1) {
                        icon = 6;
                        time = 1500;
                    }
                    var icon = response.code == 1 ? 6 : 5;
                    layer.msg(response.msg.replace(/\n/g, "<br/>"), {icon, time}, function(){
                        if (response.code == 1) reloadOrderTable();
                    });
                });
            }
            , error: function (index, upload) {
                layer.msg('上传失败');
            }
        });

        $("#import-platfrom-order").click(function()
        {
            // platform-order-excel
            layer.open({
                title: '导入平台订单表格',
                area: ['50%', '50%'],
                content: $("#platform-order-excel").html()
                , success: function (layero, index)
                {
                    form.render('select');
                    var orderFile = upload.render({
                        elem: '#import-platfrom-order-excel'
                        , url: '{:url("file/upload",["type"=>"document"])}'
                        , accept: 'file' //普通文件
                        , exts: 'xlsx|xls|csv' // 指定类型
                        , field: "file"
                        , auto: false
                        , choose: function(obj)
                        {
                            var accountId = $("#platform-account-order option:selected").val();
                            if(!accountId)
                            {
                                $("#platform-order-error-msg").show();
                                $("#import-platfrom-order-excel").next().val('');
                                return;
                            }
                            orderFile.upload();
                        }
                        , before: function (obj) {
                            layer.load(0, {shade: false});
                        }
                        , done: function (response, index, upload) {
                            if (response.code != 1) {
                                layer.closeAll('loading');
                                var icon = response.code == 1 ? 6 : 5;
                                layer.msg(response.msg, {icon: icon, time: 1500});
                                return;
                            }
                            var accountId = $("#platform-account-order option:selected").val();
                            $.post("{:url('order/manager/import_platform_order')}", {"account_id":accountId, "path": response.data.src}).done(function (response) {
                                layer.closeAll('loading');
                                var icon = 5, time = 5500;
                                if (response.code == 1) {
                                    icon = 6;
                                    time = 1500;
                                }
                                var icon = response.code == 1 ? 6 : 5;
                                layer.msg(response.msg, {icon, time}, function(){
                                    if (response.code == 1) reloadOrderTable();
                                });
                            });
                        }
                        , error: function (index, upload) {
                            layer.msg('上传失败');
                        }
                    });
                }
                , yes: function (index, layero)
                {
                    layer.close(index);
                }
            });
        });

        // 导出订单
        $("#export-order").click(function () {
            var ids = getOrderIds('请选择要导出的订单');
            var start_date = $("#start_date").val().trim();
            if (!ids.length && !start_date) return;
            layer.load(0, {shade: false});
            $.get("{:url('order/manager/export')}", $.param({ids: ids.join(','), start_date})).done(function (response) {
                layer.closeAll('loading');
                response.code == 1
                    ? location.href = "{:url('file/download')}?file=" + response.data.src
                    : layer.msg(response.msg, {icon: 5, time: 1500});
            });
        });

        // 批量删除订单
        $("#remove-all").click(function () {
            var ids = getOrderIds('请选择要删除的订单');
            if(!ids.length) return;
            layer.confirm(`你真的要删除【${ids.length}】个订单吗？`, {btn: ['确认删除', '取消']}, function (index) {
                layer.close(index);
                layer.load(0, {shade: false});
                /*$("div.layui-table-body table tbody input[name='layTableCheckbox']:checked").each(function()
                {
                    var n = $(this).parents("tbody tr").index();  // 获取checkbox所在行的顺序
                    $("div.layui-table-body table tbody ").find("tr:eq(" + n + ")").remove(); // 移除行
                    //如果是全选移除，就将全选CheckBox还原为未选中状态
                    $("div.layui-table-header table thead div.layui-unselect.layui-form-checkbox").removeClass("layui-form-checked");
                });*/
                deleteOrder(ids.join(","), function () {
                    reloadOrderTable();
                    layer.closeAll('loading');
                });
            });
        });

        // 批量备注
        $("#batch-remark").click(function () {
            var ids = getOrderIds("请选择要备注的订单");
            if(!ids.length) return;
            layer.prompt({title: '批量备注订单', formType: 2}, function (text, index) {
                layer.close(index);
                $.post("{:url('order/manager/save')}", {
                    order_id: ids.join(","),
                    field: "remark",
                    value: text
                }).done(function (response) {
                    var icon = response.code == 1 ? 6 : 5;
                    layer.msg(response.msg, {icon: icon, time: 1500});
                    reloadOrderTable();
                });
            });
        });

        // 点击筛选订单状态
        $("body").on("click", ".order-status-select li", function () {
            var $this = $(this);
            $this.siblings().find("a").removeClass("active");
            $this.find("a").addClass("active");
        });

        // 下拉框多选
        $(".more-xm-select").each(function()
        {
            var name = $(this).attr("name");
            var prop = {
                "select-account":{
                    name: "username",
                    value: "account_id"
                },
                "select-country":{
                    name: "name_ch",
                    value: "code_two"
                },
                "select-logistics":{
                    name: "carrier_name",
                    value: "carrier_name"
                },
                "select-channel":{
                    name: "channel_name",
                    value: "channel_id"
                }
            };
            if(!prop[name]) return;
            var json = JSON.parse($(this).find("span").text());
            var xargs = {
                el: this,
                prop: prop[name],
                tips: $(this).attr("tips"),
                name: name,
                autoRow: true,
                filterable: true,
                data: json,
                on: function(data)
                {
                    setTimeout(()=>{reloadOrderTable();}, 300);
                }
            };
            layui.xmSelect.render(xargs);
        });

        // 修改订单状态
        $("#batch-edit-status").click(function ()
        {
            var ids = getOrderIds("请选择要修改的订单");
            if(!ids.length) return;
            openEditOrderStatus(function(params)
            {
                params["order_id"] = ids.join(',');
                $.post("{:url('/order/manager/save')}", params).done(function (response) {
                    var icon = response.code == 1 ? 6 : 5;
                    layer.msg(response.msg, {icon: icon, time: 1500});
                    reloadOrderTable();
                });
            });
        });

        // 批量打印
        $("#batch-print").click(function () {
            var data = table.checkStatus("commodity").data;
            if (data.length < 1) {
                layer.msg("请选择要打印的订单");
                return;
            }
            var ids = [], labels = [];
            for (let i in data) {
                if (data[i].label_url != "") {
                    ids.push(data[i].order_id);
                    labels.push(data[i].label_url);
                }
            }
            if (ids.length < 1) {
                layer.msg("未生成面单", {icon: 5, time: 1500});
                return;
            }
            printLabel(ids.join(","));
        });

        // 添加黑名单
        $("#batch-add-black").click(function()
        {
            var ids = getOrderIds("请选择要加入黑名单的订单");
            if(!ids.length) return;
            layer.prompt({
                title: '加入黑名单原因'
                , formType: 2
                , value: ' '
            }, function(text, index)
            {
                layer.close(index);
                layer.load(0, {shade: false});
                $.post("{:url('/cus/black/push')}", {ids, reason: text}).done(function(response)
                {
                    layer.closeAll('loading');
                    var icon = response.code == 1 ? 6 : 5;
                    layer.msg(response.msg, {icon: icon, time: 1500});
                });
            });
        });

        // 再次发货
        $("#batch-add-again").click(function()
        {
            var ids = getOrderIds("请选择要再次发货的订单");
            if(!ids.length) return;
            layer.load(0, {shade: false});
            $.post("{:url('again')}", {ids}).done(function(response)
            {
                layer.closeAll('loading');
                var icon = response.code == 1 ? 6 : 5;
                layer.msg(response.msg, {icon: icon, time: 1500});
                if(response.code == 1) reloadOrderTable();
            });
        });

        // 释放库存
        $("#batch-unlock").click(function()
        {
            var ids = getOrderIds("请选择要释放库存的订单");
            if(!ids.length) return;
            layer.load(0, {shade: false});
            $.get("{:url('/order/manager/unlock')}", {ids: ids.join(',')}).done(function(response)
            {
                layer.closeAll('loading');
                var icon = response.code == 1 ? 6 : 5;
                layer.msg(response.msg, {icon: icon, time: 1500});
                if(response.code == 1) reloadOrderTable();
            });
        });

        // 占用库存
        $("#batch-lock").click(function()
        {
            var ids = getOrderIds("请选择要占用库存的订单");
            if(!ids.length) return;
            layer.load(0, {shade: false});
            $.get("{:url('/order/manager/lock')}", {ids: ids.join(',')}).done(function(response)
            {
                layer.closeAll('loading');
                var icon = response.code == 1 ? 6 : 5;
                layer.msg(response.msg, {icon: icon, time: 1500});
                if(response.code == 1) reloadOrderTable();
            });
        });

        // 生成采购单
        $("#batch-purchase").click(function()
        {
            var ids = getOrderIds("请选择要生成采购单的订单");
            if(!ids.length) return;
            layer.load(0, {shade: false});
            $.get("{:url('/order/manager/purchase')}", {ids: ids.join(',')}).done(function(response)
            {
                layer.closeAll('loading');
                var icon = response.code == 1 ? 6 : 5;
                layer.msg(response.msg, {icon: icon, time: 1500});
                if(response.code == 1) reloadOrderTable();
            });
        });

        // 修复订单
        $("#batch-repair").click(function()
        {
            layer.load(0, {shade: false});
            $.get("{:url('/order/manager/repair')}").done(function(response)
            {
                layer.closeAll('loading');
                var icon = response.code == 1 ? 6 : 5;
                layer.msg(response.msg, {icon: icon, time: 1500});
                if(response.code == 1) reloadOrderTable();
            });
        });

        // 申报订单
        $("#batch-declare").click(function()
        {
            var ids = getOrderIds("请选择要申报的订单");
            if(!ids.length) return;
            layer.load(0, {shade: false});
            $.get("{:url('/order/manager/declare')}", {ids: ids.join(',')}).done(function(response)
            {
                layer.closeAll('loading');
                var icon = response.code == 1 ? 6 : 5;
                layer.msg(response.msg, {icon: icon, time: 1500});
            });
        });

        // 下载发票
        $("#batch-download-invoice").click(function()
        {
            var ids = getOrderIds("请选择要生成发票的订单");
            if(!ids.length) return;
            var url = "{:url('/order/invoice/render')}" + "?ids=" + ids.join(",") + "&random=" + Math.random();
            layer.load(0, {shade: false});
            $.get(url).done(function(response)
            {
                layer.closeAll('loading');
                if(response.code != 1)
                {
                    layer.msg(response.msg, {icon: 5, time: 1500});
                    return false;
                }
                location.href = "{:url('file/download')}?file=" + response.data.path
            });
        });

        // 点击筛选
        $(".order-select li").click(function () {
            var $this = $(this);
            $this.siblings().find("a").removeClass("active");
            $this.find("a").addClass("active");
            reloadOrderTable();
        });

        // 展示更多筛选项
        $(".order-select-down").click(function () {
            var $this = $(this), $box = $(".screen-box");
            $box.toggle("fast");
            if ($box.data("c")) {
                $box.data("c", 0);
                $this.find("span").text("更多");
                $this.find("i").removeClass("fa-angle-double-up").addClass("fa-angle-double-down");
            } else {
                $box.data("c", 1);
                $this.find("span").text("收起");
                $this.find("i").removeClass("fa-angle-double-down").addClass("fa-angle-double-up");
            }
        });
        // 重置表格大小
        resetTableSize(table, "commodity");

        /**
         * 获取订单id
         * @param msg
         * @returns {[]}
         */
        function getOrderIds(msg)
        {
            var data = table.checkStatus("commodity").data
                , ids = [];
            if (data.length < 1) {
                layer.msg(msg || "请选择要处理的订单");
                return ids;
            }
            for (let i in data) ids.push(data[i].order_id);
            return ids;
        }

        /**
         * 打印面单
         */
        function printLabel(ids)
        {
            layer.load(0, {shade: false});
            var url = "{:url('/order/manager/batch_print')}?ids=" + ids;
            $.get(url).done(function(response)
            {
                layer.closeAll('loading');
                if(response.code != 1)
                {
                    layer.msg(response.msg, {icon: 5, time: 3000});
                    return false;
                }
                printJS({printable: response.data.file, type: 'pdf', base64: true, showModal:true})
            });
        }
    });
</script>
{/block}
